package com.hua.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hua.common.Response;
import com.hua.common.ResponseCode;
import com.hua.domain.User;
import com.hua.exception.BusinessException;
import com.hua.mapper.DiscountcardMapper;
import com.hua.service.impl.UserServiceImpl;
import com.hua.util.JwtUtil;
import com.hua.util.RedisCache;
import com.hua.util.ResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.hua.constant.RedisConstant.REDIS_USER_ID;

/**
 * ClassName:UserContoller
 * Package:com.hua.controller
 * Description:
 * @date: 2022/10/18 10:55
 * @author:ChenJH
 */
@Api("操作用户相关的接口")
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private RedisCache redisCache;

    @Resource
    private UserServiceImpl userServiceImpl;

    private static final String USER_ID = "userId";


    @ApiOperation("登录接口")
    @PostMapping("/login")
    public Response<User> toLogin(@RequestBody User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserAccount, user.getUserAccount());
        User userByAccount = userServiceImpl.getOne(queryWrapper);
        String token=null;
        if (userByAccount!=null){
            token = JwtUtil.createJWT(userByAccount.getUserId().toString());
        }
        if(!Objects.isNull(userByAccount)&&userByAccount.getUserStatus()==2){
            throw new BusinessException(ResponseCode.SYSTEM_ERROR, "你的号已经被封禁");
        }

        if (!Objects.isNull(userByAccount)&& !(user.getUserAccount().length() > 6)) {
            if (!userByAccount.getUserAccount().equals(user.getUserAccount()) ||
                    !userByAccount.getUserPassword().equals(user.getUserPassword())) {
                throw new BusinessException(ResponseCode.LOGIN_FAIL, "登录失败");
            }
            redisCache.setCacheObject(REDIS_USER_ID + userByAccount.getUserId(), userByAccount, 30, TimeUnit.MINUTES);
            redisCache.setCacheObject(USER_ID, +userByAccount.getUserId(), 30, TimeUnit.MINUTES);
            userByAccount.setUserPassword(null);
            System.out.println(userByAccount);
            return ResultUtils.success(ResponseCode.SUCCESS, userByAccount, token, "登录成功");
        } else {
            if (Objects.isNull(userByAccount)) {
                userServiceImpl.save(user);
            }
            return ResultUtils.success(ResponseCode.SUCCESS, userByAccount, token, "登录成功");
        }
    }




    @ApiOperation("退出接口")
    @PostMapping("/logOut")
    public Response<String> toLogOut() {
        Integer userId = redisCache.getCacheObject(USER_ID);
        User userInfo = redisCache.getCacheObject(REDIS_USER_ID + userId);
        if (userInfo == null) {
            throw new BusinessException(ResponseCode.NOT_LOGIN, "用户位登录");
        } else {
            redisCache.deleteObject(USER_ID);
            redisCache.deleteObject(REDIS_USER_ID + userId);
//            return new Response(200,"退出成功");
            return ResultUtils.success(ResponseCode.LOGOUT_SUCCESS, "退出成功");
        }
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/getUser")
    public User getUser() {
        Integer userId = redisCache.getCacheObject(USER_ID);
        User user = redisCache.getCacheObject(REDIS_USER_ID + userId);
        if (user == null) {
            throw new BusinessException(ResponseCode.SESSION_EXPIRED);
        }
        user.setUserPassword(null);
        return user;
    }

    @ApiOperation("发送优惠卷")
    @PostMapping("/sendDiscount/{discountId}")
    public Response sendDiscount(@PathVariable Integer discountId) {
      return userServiceImpl.sendDisCount(discountId);
    }

    @PostMapping("/getDiscont/{userId}/{discountCardId}")
    @ApiOperation("抢卷")
    public Response<String> getDiscount(@PathVariable(value = "userId") Integer userId,@PathVariable(value = "discountCardId") Integer discountCardId) {
        return userServiceImpl.getDiscount(userId,discountCardId);
    }
}
